package org.keyyond.ms.scheduler.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerContext;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("quartz")
@RestController
public class KeyyondMsQuartzDynamicController {

	@Autowired
	SchedulerFactoryBean schedulerFactoryBean;

	@PostMapping("/changeCron")
	public void changeCron(HttpServletRequest request) throws Exception {
		String newCron = request.getParameter("newCron");
		String jobName = request.getParameter("triggerName");
		String jobGroup = request.getParameter("triggerGroup");
		Scheduler scheduler = schedulerFactoryBean.getScheduler();
		// SchedulerContext context = scheduler.getContext();
		TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);

		CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
		String currentCron = trigger.getCronExpression();// 当前Trigger使用的
		System.out.println(currentCron);
		System.out.println(newCron);
		if (currentCron.equals(newCron)) {
			// 如果当前使用的cron表达式和从数据库中查询出来的cron表达式一致，则不刷新任务
		} else {
			// 表达式调度构建器
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
					.cronSchedule(newCron);
			// 按新的cronExpression表达式重新构建trigger
			trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
			trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
					.withSchedule(scheduleBuilder).build();
			// 按新的trigger重新设置job执行
			scheduler.rescheduleJob(triggerKey, trigger);
			currentCron = newCron;
		}
	}

	/**
	 * 
	 * Description: 得到job的详细信息
	 * 
	 * @param jobId
	 *            job的ID
	 * @param jobGroupId
	 *            job的组ID
	 * @return job的详细信息,如果job不存在则返回null
	 * @Author lanzhongliang
	 * @Create 2013-7-19 下午04:07:08
	 */
	public JobDetail getJobDetail(String jobId, String jobGroupId) {
		if (StringUtils.isEmpty(jobId) || StringUtils.isEmpty(jobGroupId)) {
			return null;
		}
		try {
			Scheduler scheduler = schedulerFactoryBean.getScheduler();
			JobKey jobKey = new JobKey(jobId, jobGroupId);
			return scheduler.getJobDetail(jobKey);
		} catch (SchedulerException e) {
			e.printStackTrace();
			return null;
		}
	}

}
